package com.frame.mysql.config;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 执行main方法控制台输入模块表明回车自动生成对象项目目录
 * 需要修改模板路径
 * 数据连接、密码
 * parentPath包名
 */
public class MyBatisPlusGenerator {

    static String author = "chai";
    static String url = "jdbc:mysql://localhost:3306/vhr?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    static String driverName = "com.mysql.cj.jdbc.Driver";
    static String userName = "root";
    static String password = "";
    /**
     * 配置模板引擎velocity 的位置
     */
    static String[] templatesPath = {"/templates/entity.java.vm", "/templates/mapper.java.vm", "/templates/mapper.xml.vm", "/templates/service.java.vm", "/templates/serviceImpl.java.vm", "/templates/controller.java.vm"};
    static String tablePrefix = "";
    static String tableName = "hr";
    static String fieldPrefix = "";
    static String moduleName = tableName.replace(fieldPrefix, "");
    static String modulePath = "/service/api";
    static String parentPath = "com.frame.api.business";
    static String packagePath = parentPath.replace(".", "/");
    /**
     * 文件覆盖
     */
    static boolean fileOverride = true;
    /**
     * 如果为true 则不生成相关文件
     * 比如修改了字段，只重生成xml和entity 那么 fileOverride = true,  entity = true, xml = true
     */
    static boolean entity = true;
    /**
     * 为false时会在mapper包下创建xml文件
     */
    static boolean mapper = true;
    static boolean xml = true;
    static boolean service = true;
    static boolean serviceImpl = true;
    static boolean controller = true;
    static String projectPath = "";

    public static void main(String[] args) {
        //代码生成器
        AutoGenerator mpg = new AutoGenerator();

        //全局配置
        GlobalConfig gc = new GlobalConfig();
        //获取用户当前的工作目录
        projectPath = System.getProperty("user.dir") + modulePath;
        gc.setOutputDir(projectPath+"/src/main/java")
                .setAuthor(author)
                .setOpen(false)
                .setFileOverride(fileOverride)
                .setEnableCache(false)
                .setSwagger2(true)
                .setBaseResultMap(true)
                .setIdType(IdType.AUTO)
                .setBaseResultMap(true)
                .setBaseColumnList(true)
                .setEntityName("%s")
                .setMapperName("%sMapper")
                .setXmlName("%sMapper")
                .setServiceName("%sService")
                .setServiceImplName("%sServiceImpl")
                .setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        //数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url)
                .setDriverName(driverName)
                .setUsername(userName)
                .setPassword(password);
        mpg.setDataSource(dsc);

        //包配置
        PackageConfig pc = new PackageConfig();
         pc.setParent(parentPath)
                 .setModuleName(moduleName);
        mpg.setPackageInfo(pc);

        //配置模板
        TemplateConfig tc = new TemplateConfig();
        //配置自定义输出模板
        if (entity) {
            tc.setEntity(null);
        }
        if (mapper) {
            tc.setMapper(null);
        }
        if (xml) {
            tc.setXml(null);
        }
        if (controller) {
            tc.setController(null);
        }
        if (service) {
            tc.setService(null);
        }
        if (serviceImpl) {
            tc.setServiceImpl(null);
        }

        mpg.setTemplate(tc);

        //自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("ControllerMapping", "/api/" + moduleName);
                this.setMap(map);
            }
        };

        //自定义输出位置
        List<FileOutConfig> focList = new ArrayList();
        //自定义配置回呗优先输出
        FileOutConfig entity = new FileOutConfig(templatesPath[0]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //自定义输出文件名，如果你Entity设置了前后缀、此处注意名称会跟着发生变化
                return getJavaPath("entity", tableInfo.getEntityName());
            }
        };
        FileOutConfig mapper = new FileOutConfig(templatesPath[1]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //自定义输出文件名，如果你Entity设置了前后缀、此处注意名称会跟着发生变化
                return getJavaPath("mapper", tableInfo.getMapperName());
            }
        };
        FileOutConfig xml = new FileOutConfig(templatesPath[2]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + ".xml";
            }
        };
        FileOutConfig service = new FileOutConfig(templatesPath[3]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getJavaPath("service", tableInfo.getServiceName());
            }
        };
        FileOutConfig impl = new FileOutConfig(templatesPath[4]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getJavaPath("service/impl", tableInfo.getServiceImplName());
            }
        };
        FileOutConfig controller = new FileOutConfig(templatesPath[5]) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getJavaPath("controller", tableInfo.getControllerName());
            }
        };
        focList.add(entity);
        focList.add(mapper);
        focList.add(xml);
        focList.add(service);
        focList.add(impl);
        focList.add(controller);

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //数据库表策略配置
        StrategyConfig sc = new StrategyConfig();
        //_下划线改成驼峰命名法
        sc.setNaming(NamingStrategy.underline_to_camel)
        .setEntityLombokModel(true)
        .setRestControllerStyle(true)
        .setFieldPrefix(fieldPrefix)
        .setChainModel(true)
        //写于父类中的公共字段
        .setInclude(tableName)
        .setTablePrefix(tablePrefix);

        mpg.setStrategy(sc);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
    }

    private static String getJavaPath(String module, String tableInfo) {
        StringBuilder sb = new StringBuilder();
        sb.append(projectPath + "/src/main/java/" + packagePath + "/" + moduleName)
                .append("/" + module + "/")
                .append(tableInfo + ".java");
        return sb.toString();
    }
}